/**
 * Created by hengyu on 2019/1/15.
 */
/**
 * 添加模型
 * state: true启用，false关闭
 */
function createModel(state, length, width, height, color, rotate) {
    if (state) {
        var viewer = mapApp.cesiumMap.viewer;
        mapApp.cesiumMap.designCityF = new Object()
        var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        mapApp.cesiumMap.designCityF.drawHandler = handler;
        //设置单击事件的处理句柄
        handler.setInputAction(function (movement) {
            //获取单击位置坐标
            //var cartesian3 = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(movement.position.x, movement.position.y));
            var cartesian3 = viewer.scene.pickPosition(movement.position)
            var cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
            var lng = Cesium.Math.toDegrees(cartographic.longitude);
            var lat = Cesium.Math.toDegrees(cartographic.latitude);
            var h = cartographic.height;

            var heading = Cesium.Math.toRadians(rotate);
            var pitch = 0;
            var roll = 0;
            var orientation = Cesium.Transforms.headingPitchRollQuaternion(cartesian3, new Cesium.HeadingPitchRoll(heading, pitch, roll));

            var entity = new Cesium.Entity({
                name: 'box',
                //position:Cesium.Cartesian3.fromDegrees(lng,lat,0),
                position: cartesian3,
                orientation: orientation,
                box: {
                    dimensions: new Cesium.Cartesian3(length, width, height),
                    //material: new Cesium.ColorMaterialProperty(new Cesium.Color(10, 10, 10)),
                    material: Cesium.Color.fromAlpha(Cesium.Color.fromCssColorString(color), 0.8),
                    fill: true,
                    outline: true,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 40
                },
                name: "chengShiSheJi"
            });
            entity.position = new Cesium.Cartesian3.fromDegrees(lng, lat, h + height / 2)
            viewer.entities.add(entity);
            handler.destroy();
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    } else {
        var viewer = mapApp.cesiumMap.viewer
        var entities = viewer.entities.values
        for (var i = 0; i < entities.length; i++) {
            viewer.entities.remove(entities[i])
            i--
        }
        //mapApp.cesiumMap.designCityF.drawHandler.destroy();
    }
}

/**
 * 添加自定义模型面
 * @param state: true启用，false清空所有模型并关闭
 * @param height:模型高度，默认100米
 * @param color:模型CSS颜色，默认白色
 * @param alpha:透明度，不透明传1，默认0.8
 */
function createModel2(state, height, color, alpha) {
    if (state) {
        var viewer = mapApp.cesiumMap.viewer

        if (!mapApp.cesiumMap.designCityF) {
            mapApp.cesiumMap.designCityF = new Object()
        }
        if (mapApp.cesiumMap.designCityF.drawHandler) {
            mapApp.cesiumMap.designCityF.drawHandler.clear()
            mapApp.cesiumMap.designCityF.drawHandler.deactivate()
        }
        var handlerPolygon = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Polygon, clampMode)
        mapApp.cesiumMap.designCityF.drawHandler = handlerPolygon
        handlerPolygon.drawEvt.addEventListener(function (result) {
            var tempEntity = new Cesium.Entity({
                polygon: {
                    height: 0,
                    hierarchy: new Cesium.PolygonHierarchy(result.object.positions),
                    extrudedHeight: Number(height) ? Number(height) : 100,
                    material: Cesium.Color.fromAlpha(Cesium.Color.fromCssColorString(color ? color : "#FFFFFF"), Number(alpha) ? Number(alpha) : 0.8),
                    outline: true,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 20,
                    shadow: Cesium.ShadowMode.ENABLED

                },
                name: "chengShiSheJi"
            });

            viewer.entities.add(tempEntity);
        });
        handlerPolygon.activate();

    } else {
        // mapApp.cesiumMap.designCityF.drawHandler.polygon.show = false;
        // mapApp.cesiumMap.designCityF.drawHandler.polyline.show = false;

        if (mapApp.cesiumMap.designCityF.drawHandler) {
            mapApp.cesiumMap.designCityF.drawHandler.clear()
            mapApp.cesiumMap.designCityF.drawHandler.deactivate()
        }
        var viewer = mapApp.cesiumMap.viewer
        var entities = viewer.entities.values
        for (var i = 0; i < entities.length; i++) {
            if (entities[i].name = "chengShiSheJi") {
                viewer.entities.remove(entities[i])
                i--
            }
        }
    }
}


/**
 * 添加自定义模型线
 * @param state: true启用，false清空所有模型并关闭
 * @param height:模型高度，默认100米
 * @param color:模型CSS颜色，默认白色
 * @param alpha:透明度，不透明传1，默认0.8
 */
function createModel3(state, height, color, alpha) {
    if (state) {
        var viewer = mapApp.cesiumMap.viewer

        if (!mapApp.cesiumMap.designCityF) {
            mapApp.cesiumMap.designCityF = new Object()
        }
        if (mapApp.cesiumMap.designCityF.drawHandler) {
            mapApp.cesiumMap.designCityF.drawHandler.clear()
            mapApp.cesiumMap.designCityF.drawHandler.deactivate()
        }
        var handlerLine = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Line, clampMode);
        mapApp.cesiumMap.designCityF.drawHandler = handlerLine;
        //激活绘制线
        handlerLine.activate();
        handlerLine.activeEvt.addEventListener(function (isActive) {
            if (isActive == true) {
                viewer.enableCursorStyle = false;
                viewer._element.style.cursor = '';
                $('body').removeClass('drawCur').addClass('drawCur');
            }
            else {
                viewer.enableCursorStyle = true;
                $('body').removeClass('drawCur');
            }
        });

        //鼠标移动监听事件
        handlerLine.movingEvt.addEventListener(function (windowPosition) {
            if (windowPosition.x < 210 && windowPosition.y < 120) {
                tooltip.setVisible(false);
                return;
            }
            if (handlerPolygon.isDrawing) {
                tooltip.showAt(windowPosition, '<p>右键单击结束绘制</p>');
            }
            else {

            }
        });

        //绘制完成监听事件

        handlerLine.drawEvt.addEventListener(function (result) {
            var lineEntity = new Cesium.Entity({
                polyline: {
                    width: 10,
                    hierarchy: new Cesium.PolygonHierarchy(result.object.positions),
                    extrudedHeight: Number(height) ? Number(height) : 100,
                    material: Cesium.Color.fromAlpha(Cesium.Color.fromCssColorString(color ? color : "#FFFFFF"), Number(alpha) ? Number(alpha) : 0.8),
                    outline: true,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 20
                },
                name: "chengShiSheJixian"
            });

            viewer.entities.add(lineEntity);
        });

    } else {
        if (mapApp.cesiumMap.designCityF.drawHandler) {
            mapApp.cesiumMap.designCityF.drawHandler.clear()
            mapApp.cesiumMap.designCityF.drawHandler.deactivate()
        }
        var viewer = mapApp.cesiumMap.viewer
        var entities = viewer.entities.values
        for (var i = 0; i < entities.length; i++) {
            if (entities[i].name = "chengShiSheJixian") {
                viewer.entities.remove(entities[i])
                i--
            }
        }
    }
}


/**
 * 断面剖面分析
 * @param state
 */
function pouMianFenXi(state) {
    if (state) {
        var viewer = mapApp.cesiumMap.viewer
        if (!mapApp.cesiumMap.pouMianF) {
            mapApp.cesiumMap.pouMianF = new Object()
        }
        if (mapApp.cesiumMap.pouMianF.drawHandler) {
            mapApp.cesiumMap.pouMianF.drawHandler.clear()
            mapApp.cesiumMap.pouMianF.drawHandler.deactivate()
        }
        var handlerLine = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Line, clampMode)
        mapApp.cesiumMap.pouMianF.drawHandler = handlerLine
        // handlerLine.activeEvt.addEventListener(function(isActive){
        //     console.log(isActive)
        // });
        handlerLine.drawEvt.addEventListener(function (result) {
            var frameName = window.top.getdmfxFrames();
            var ellipsoid = mapApp.cesiumMap.viewer.scene.globe.ellipsoid;
            var line1 = result.object.positions[0]
            var line2 = result.object.positions[1]
            var cartesian3_1 = new Cesium.Cartesian3(line1.x, line1.y, line1.z);
            var cartesian3_2 = new Cesium.Cartesian3(line2.x, line2.y, line2.z);
            var cartographic1 = ellipsoid.cartesianToCartographic(cartesian3_1);
            var cartographic2 = ellipsoid.cartesianToCartographic(cartesian3_2);
            var lat1 = Cesium.Math.toDegrees(cartographic1.latitude);
            var lng1 = Cesium.Math.toDegrees(cartographic1.longitude);

            var lat2 = Cesium.Math.toDegrees(cartographic2.latitude);
            var lng2 = Cesium.Math.toDegrees(cartographic2.longitude);
            var geometry = new ol.geom.LineString([[lng1, lat1], [lng2, lat2]])
            var line1feature = new ol.Feature({
                geometry: geometry.transform("EPSG:4326", "EPSG:3857")
            })
            var format = new ol.format.WKT();
            var lineWKT = format.writeFeature(line1feature);
            window.top.frames[frameName].getImg(lineWKT);


        });
        handlerLine.movingEvt.addEventListener(function (windowPosition) {
            if (handlerLine.isDrawing) {
                if (handlerLine.polyline.positions.length > 2) {
                    handlerLine.polyline.positions.pop()
                    var ellipsoid = mapApp.cesiumMap.viewer.scene.globe.ellipsoid;
                    var line1 = handlerLine.polyline.positions[0]
                    var line2 = handlerLine.polyline.positions[1]
                    var cartesian3_1 = new Cesium.Cartesian3(line1.x, line1.y, line1.z);
                    var cartesian3_2 = new Cesium.Cartesian3(line2.x, line2.y, line2.z);
                    var cartographic1 = ellipsoid.cartesianToCartographic(cartesian3_1);
                    var cartographic2 = ellipsoid.cartesianToCartographic(cartesian3_2);
                    var lat1 = Cesium.Math.toDegrees(cartographic1.latitude);
                    var lng1 = Cesium.Math.toDegrees(cartographic1.longitude);

                    var lat2 = Cesium.Math.toDegrees(cartographic2.latitude);
                    var lng2 = Cesium.Math.toDegrees(cartographic2.longitude);
                    var geometry = new ol.geom.LineString([[lng1, lat1], [lng2, lat2]])
                    var line1feature = new ol.Feature({
                        geometry: geometry.transform("EPSG:4326", "EPSG:3857")
                    })
                    var format = new ol.format.WKT();
                    var lineWKT = format.writeFeature(line1feature);
                    handlerLine.deactivate()
                    var frameName = window.top.getdmfxFrames();
                    window.top.frames[frameName].getImg(lineWKT);
                }
            }
        });
        handlerLine.activate();
    } else {
        mapApp.cesiumMap.pouMianF.drawHandler.clear()
        mapApp.cesiumMap.pouMianF.drawHandler.deactivate()
    }
}

/**
 * 道路拓宽分析
 * @param state 1开启，0关闭
 */
function DLTKFenXi(state) {
    if (state) {
        if (!mapApp.cesiumMap.daoLuTuoKuanF) {
            mapApp.cesiumMap.daoLuTuoKuanF = new Object()
            mapApp.cesiumMap.daoLuTuoKuanF.lines = []
            mapApp.cesiumMap.daoLuTuoKuanF.handlers = []
        }
        var viewer = mapApp.cesiumMap.viewer;
        var scene = viewer.scene;
        var PolyLinePrimitive = (function () {
            function _(positions) {
                this.options = {
                    polyline: {
                        show: true,
                        positions: [],
                        material: Cesium.Color.CORNFLOWERBLUE,
                        width: 5
                    }
                };
                this.positions = positions;
                this._init();
            }

            _.prototype._init = function () {
                var _self = this;
                var _update = function () {
                    return _self.positions;
                };
                //实时更新polyline.positions
                this.options.polyline.positions = new Cesium.CallbackProperty(_update, false);
                mapApp.cesiumMap.daoLuTuoKuanF.lines.push(viewer.entities.add(this.options));
            };

            return _;
        })();
        var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
        mapApp.cesiumMap.daoLuTuoKuanF.handlers.push(handler)
        var positions = [];
        var poly = undefined;
        handler.setInputAction(function (movement) {
            var cartesian = viewer.scene.pickPosition(movement.position)
            cartesian.z = cartesian.z + 0.2
            //var cartesian = scene.camera.pickEllipsoid(movement.position,scene.globe.ellipsoid);
            if (positions.length == 2) {
                positions.pop()
                positions.push(cartesian);
                handler.destroy();
                if (mapApp.cesiumMap.daoLuTuoKuanF.lines.length > 1) {
                    var line1 = mapApp.cesiumMap.daoLuTuoKuanF.linePositons[0]
                    var line2 = positions
                    var ellipsoid = mapApp.cesiumMap.viewer.scene.globe.ellipsoid;
                    var cartesian3_1 = new Cesium.Cartesian3(line1[0].x, line1[0].y, line1[0].z);
                    var cartesian3_2 = new Cesium.Cartesian3(line1[1].x, line1[1].y, line1[1].z);
                    var cartographic1 = ellipsoid.cartesianToCartographic(cartesian3_1);
                    var cartographic2 = ellipsoid.cartesianToCartographic(cartesian3_2);
                    var lat1 = Cesium.Math.toDegrees(cartographic1.latitude);
                    var lng1 = Cesium.Math.toDegrees(cartographic1.longitude);

                    var lat2 = Cesium.Math.toDegrees(cartographic2.latitude);
                    var lng2 = Cesium.Math.toDegrees(cartographic2.longitude);

                    var geometry1 = new ol.geom.LineString([[lng1, lat1], [lng2, lat2]]);
                    var line1feature1 = new ol.Feature({
                        geometry: geometry1
                    })
                    var format = new ol.format.WKT();
                    var lineWKT1 = format.writeFeature(line1feature1);

                    var cartesian3_1 = new Cesium.Cartesian3(positions[0].x, positions[0].y, positions[0].z);
                    var cartesian3_2 = new Cesium.Cartesian3(positions[1].x, positions[1].y, positions[1].z);
                    var cartographic1 = ellipsoid.cartesianToCartographic(cartesian3_1);
                    var cartographic2 = ellipsoid.cartesianToCartographic(cartesian3_2);
                    var lat1 = Cesium.Math.toDegrees(cartographic1.latitude);
                    var lng1 = Cesium.Math.toDegrees(cartographic1.longitude);

                    var lat2 = Cesium.Math.toDegrees(cartographic2.latitude);
                    var lng2 = Cesium.Math.toDegrees(cartographic2.longitude);

                    var geometry1 = new ol.geom.LineString([[lng1, lat1], [lng2, lat2]]);
                    var line1feature1 = new ol.Feature({
                        geometry: geometry1
                    })
                    var lineWKT2 = format.writeFeature(line1feature1);

                    DLTKFenXi(false);
                    var frameName = window.top.getdmfxFrames();
                    window.top.frames[frameName].getDltk(lineWKT1, lineWKT2);
                } else {
                    mapApp.cesiumMap.daoLuTuoKuanF.linePositons = []
                    mapApp.cesiumMap.daoLuTuoKuanF.linePositons.push(positions)
                    DLTKFenXi(true)
                }
                return
            }
            positions.push(cartesian);
            if (positions.length == 1) {
                handler.setInputAction(function (movement) {
                    var cartesian = viewer.scene.pickPosition(movement.endPosition)
                    if (positions.length == 1) {
                        positions.push(cartesian)
                    }
                    if (positions.length >= 2) {
                        if (!Cesium.defined(poly)) {
                            poly = new PolyLinePrimitive(positions);
                        } else {
                            positions.pop();
                            positions.push(cartesian);
                        }
                    }
                }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    } else {
        if (mapApp.cesiumMap.daoLuTuoKuanF) {
            for (var i = 0; i < mapApp.cesiumMap.daoLuTuoKuanF.handlers.length; i++) {
                if (!mapApp.cesiumMap.daoLuTuoKuanF.handlers[i].isDestroyed()) {
                    mapApp.cesiumMap.daoLuTuoKuanF.handlers[i].destroy()
                }
            }
            if (mapApp.cesiumMap.daoLuTuoKuanF.handlers.length == 2) {
                for (var i = 0; i < mapApp.cesiumMap.daoLuTuoKuanF.lines.length; i++) {
                    mapApp.cesiumMap.viewer.entities.remove(mapApp.cesiumMap.daoLuTuoKuanF.lines[i])
                }
                mapApp.cesiumMap.daoLuTuoKuanF.handlers = []
            }
            mapApp.cesiumMap.daoLuTuoKuanF.lines = []
        }
        mapApp.cesiumMap.viewer.entities.removeById("identifyDLTK")
    }
}

/**
 * 道路拓宽标识面
 * @param wkt
 */
function identifyAreaDLTK(wkt) {
    if (wkt) {
        var lonLatArr = /\(\((.*)\)\)/ig.exec(wkt)[1].replace(/,/ig, " ").split(" ").map(Number)
        var viewer = mapApp.cesiumMap.viewer;
        viewer.entities.add({
            id: 'identifyDLTK',
            name: '单体化标识面',
            polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(lonLatArr),
                material: Cesium.Color.fromAlpha(Cesium.Color.fromCssColorString("#1E90FF"), 0.3),
            },
            clampToS3M: true
        });
    }

}
